package com.qingcloud.df.executor.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

public class ProcessUtils {


    private static final Logger logger = LoggerFactory.getLogger(ProcessUtils.class);

    /**
     * 关闭进程
     */
    public static void gentleClose(final Process process, final long timeout, final TimeUnit timeUnit) {

        if (process == null) {
            return;
        }

        if (process.info() != null) {
            process.info().commandLine().ifPresent(commandLine -> logger.debug("关闭进程 {}", commandLine));
        }

        try {
            if (process.isAlive()) {
                process.waitFor(timeout, timeUnit);
            }
        } catch (final InterruptedException e) {
            logger.error("等待进程逐步完成时发生异常", e);
        }

        if (process.isAlive()) {
            closeProcess(process, Duration.of(1, ChronoUnit.MINUTES));
        }
    }
    public static void closeProcess(final Process process, final Duration lastChanceDuration) {
        if (process == null) {
            return;
        }
        try {
            process.destroy();
            process.waitFor(lastChanceDuration.toMillis(), TimeUnit.MILLISECONDS);
            if (process.isAlive()) {
                logger.warn("进程未正常的关闭,调用destroyForcibly...");
                process.destroyForcibly();
            }
        } catch (final InterruptedException e) {
            logger.error("关闭进程异常.", e);
        }
    }

    public static void wait(final Process process) {
        try {
            process.waitFor();
        } catch (final InterruptedException e) {
            logger.error("等待进程异常", e);
        }
    }
    public static void cancelProcess(final Process process) {
        closeProcess(process, Duration.of(10, ChronoUnit.SECONDS));
    }
}
